from oss import oss_interface
from cdn import cdn_pushobject
import oss2
import os
import json
import configparser
"""通过检测oss存储中的修改时间，自动预热cdn指定得url
"""
file_list = ["IOS/MGOverseasCompass_6ios.ipa", "Android/getData.apk"]
conf = configparser.SafeConfigParser()
conf.read('aliyun.conf')
AccessKeyId = conf.get('login', 'AccessKeyId')
AccessKeySecret = conf.get('login', 'AccessKeySecret')
bucket = conf.get('bucket', 'bucket')
domain = conf.get('domain', 'domain')

def check_commit(json_file):
    up_url = []
    file_last_time_dict = {}
    t1 = oss_interface.aliyun_oss(endpoint="http://oss-cn-hangzhou.aliyuncs.com",
                                  AccessKeyId=AccessKeyId,
                                  AccessKeySecret=AccessKeySecret,
                                  bucket_name=bucket)

    for i in range(len(file_list)):
        file_last_time_dict[file_list[i]] = t1.file_get(file_list[i])

    if os.path.isfile(json_file):
        with open(json_file, 'r') as load_f:
            load_dict = json.load(load_f)
        for load_key in load_dict:
            for key in file_last_time_dict:
                if load_key == key and load_dict[key] != file_last_time_dict[key]:
                    load_dict[key] = file_last_time_dict[key]

                    print("cdn 更新url为: https://"+domain+"/"+key)
                    url = "https://"+domain+"/"+key
                    up_url.append(url)
                 
                    with open(json_file, "w+") as f:
                        json.dump(load_dict, f)
                        print("json文件加载完成...")
                else:
                    continue
                    
    else:
        with open(json_file, "w+") as f:
            json.dump(file_last_time_dict, f)
            print("json文件加载完成...")
    up_url = list(set(up_url))
    print(up_url)
    return up_url     

def check_commit_push():
    url_list = check_commit("./record_push.json")
    cdn_push = cdn_pushobject.aliyun_cdn(AccessKeyId=AccessKeyId,
            AccessKeySecret=AccessKeySecret,
            endpoint='cn-hangzhou')
    for x in range(len(url_list)):
        cdn_push.push_cdn(url_list[x])

def check_commit_refresh():
    url_list = check_commit("./record_refresh.json")
    cdn_push = cdn_pushobject.aliyun_cdn(AccessKeyId=AccessKeyId,
            AccessKeySecret=AccessKeySecret,
            endpoint='cn-hangzhou')
    for x in range(len(url_list)):
        cdn_push.refresh_cdn(url_list[x])
     
def push(): 
    """推送列表中得url"""
    cdn_push = cdn_pushobject.aliyun_cdn(AccessKeyId=AccessKeyId,
                                     AccessKeySecret=AccessKeySecret,
                                     endpoint='cn-hangzhou')
    for i in range(len(file_list)):
        cdn_push.push_cdn("https://"+domain+"/"+file_list[i])
